// axios 基础实例
import 'element-plus/theme-chalk/el-message.css'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/userStore'
// import { useRouter } from 'vue-router'
import router from '@/router'
import axios from 'axios'

const request = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 35000
})
// 拦截器请求
request.interceptors.request.use(
  (config) => {
    // TODO 2. 携带token
    const useStore = useUserStore()
    const token = useStore.userInfo.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }

    return config
  },
  (err) => Promise.reject(err)
)

// 拦截器响应
request.interceptors.response.use(
  (res) => {
    // TODO 3. 处理业务失败
    // TODO 4. 摘取核心响应数据
    return res
  },
  (err) => {
    ElMessage({
      message: err.response.data.message,
      type: 'warning'
    })
    // TODO 5. 处理401错误
    if (err.response.status === 401) {
      // TODO 6. 清除本地用户数据
      // const router = useRouter()
      const useStore = useUserStore()
      useStore.logOut()
      // TODO 7. 跳转登录页
      router.push('/login')
    }

    return Promise.reject(err)
  }
)

export default request
